package com.aloha.springframework.aop.framework;

import com.aloha.springframework.aop.AdvisedSupport;
import com.aloha.springframework.aop.Advisor;
import com.aloha.springframework.aop.MethodMatcher;
import com.aloha.springframework.aop.PointcutAdvisor;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class DefaultAdvisorChainFactory implements AdvisorChainFactory {

    @Override
    public List<Advice> getInterceptorsAndDynamicInterceptionAdvice(AdvisedSupport config, Method method, Class<?> targetClass) {
        Class<?> actualClass = targetClass != null ? targetClass : method.getDeclaringClass();
        // 过滤出 和 method 匹配的所有 Advice
        return config.getAdvisors()
                .stream().filter(advisor -> advisor instanceof PointcutAdvisor).map(advisor -> (PointcutAdvisor) advisor)
                .filter(advisor -> advisor.getPointcut().getClassFilter().matches(actualClass) && advisor.getPointcut().getMethodMatcher().matches(method, actualClass))
                .map(Advisor::getAdvice)
                .collect(Collectors.toList());
    }
}
